import axios from 'axios'
import qs from 'qs'
import Config from './config.js'
import { Toast } from 'vant'
const isDev = true;

export default class Api extends Config {
    constructor() {
        super()
    }
    hideLoading() {
        if (this.loadingPop) {
            this.loadingPop.hide && this.loadingPop.hide();
        }
    }
    showProgress(data) {
        if (window.api) {
            api.showProgress({
                title: data.title,
                text: data.text,
                modal: data.modal || true
            });
        } else {

        }
    }
    hideProgress() {
        if (window.api) {
            api.hideProgress();
        }
    }
    /**
     * get请求
     */
    get(name, m, n, cb) {
        let r = new Promise((reslove, reject) => {
            // 判断url 是不是http开头
            let url = name;
            if (isDev) {
                url = this.interport.host + name;
            }
            if (name.substring(0, 4) == 'http') {
                url = name
            }
            let dataBack = m;
            // console.log(dataBack)
            if (name === 'loginFace') {
                dataBack.token = undefined
            }
            if (window.api) {
                api.ajax({
                    url: url,
                    method: 'get',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        body: dataBack
                    }
                }, function (r, e) {
                    if (r) {
                        if (r.success == 'false') {
                            reject(r)
                        } else {
                            reslove(r)
                        }
                    } else {
                        api.toast({
                            msg: e.msg || '请求服务器异常，请稍后重试',
                            duration: 2000,
                            location: 'bottom'
                        });
                        reject(e);
                    }
                });
            } else {
                axios.get(url, {
                    params: dataBack
                }).then(r => {
                    if (r.data.success == 'false') {
                        reject(r.data)
                    } else {
                        reslove(r.data)
                    }
                }).catch(e => {
                    reject(e)
                })
            }
        });
        return r;
    }
    /**
     * post请求
     */
    post(name, m, n) {
        let r = new Promise((reslove, reject) => {
            // 判断url 是不是http开头
            let url = name;
            if (isDev) {
                url = this.interport.host + name;
            }
            if (name.substring(0, 4) == 'http') {
                url = name
            }
            let dataBack = m;
            if (n) {
                for (let i in n) {
                    url = url + '&' + i + '=' + n[i]
                }
            }
            if (window.api) {
                api.ajax({
                    url: url,
                    method: 'post',
                    data: {
                        values: dataBack
                    }
                }, function (ret, err) {
                    if (ret) {
                        reslove(ret);
                    } else {
                        api.toast({
                            msg: e.msg || '请求服务器异常，请稍后重试',
                            duration: 2000,
                            location: 'bottom'
                        });
                        reject(err);
                    }
                });
            } else {
                let postData = qs.stringify(dataBack);
                // url = url + '?token=' + dataBack.token;
                axios.post(url, postData)
                    .then(r => {
                        reslove(r.data)
                    })
                    .catch(e => {
                        reject(e)
                    })
            }
        });
        return r;
    }
    getBanner(title, cb) {
        this.post("image_publish/loadInfo", {}).then(r => {
            console.log(r);
            if (r.list && r.list.length) {
                r.list.forEach(e => {
                    if (e.imageTitle == '找物业') {
                        e.imageTitle = '其他便民服务'
                    }
                    if (e.imageTitle == title) {
                        cb && cb(this.pic(e.url));
                    }
                })
            }
        })
    }
    getToken() {
        let rb = new Promise((reslove, reject) => {
            let url = this.interport.host + '/mobile/mobileInterface.shtml';
            let dataBack = {
                passWord: this.login.password,
                userName: this.login.userName,
                act: 'loginFace'
            }
            if (window.api) {
                api.ajax({
                    url: url,
                    method: 'get',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        body: dataBack
                    }
                }, function (r, e) {
                    if (r) {
                        if (r.success == 'false') {
                            reslove(0)
                        } else {
                            reslove(r.Data[0].token)
                        }
                    } else {
                        reslove(0)
                    }
                });
            } else {
                axios.get(url, {
                    params: dataBack
                }).then(r => {
                    if (r.data.success == 'false') {
                        reslove(0);
                    } else {
                        reslove(r.data.Data[0].token);
                    }
                }).catch(e => {
                    reslove(0);
                })
            }
        })
        return rb
    }
    dealToken(m, token, timestampNow) {
        let rb = new Promise((reslove, reject) => {
            if (token) {
                this.setApiData('tokendata', {
                    token: token,
                    timestamp: timestampNow
                })
                reslove({
                    ...m,
                    token: token
                })
            } else {
                reslove({
                    ...m
                })
            }
        })
        return rb;
    }
    delData(m) {
        let rb = new Promise((reslove, reject) => {
            let timestampNow = Date.parse(new Date()) / 1000;
            if (this.tokendata) {
                let min = (timestampNow - this.tokendata.timestamp);
                let i = this.ExpirationDate || 1800;
                if (min > i) {
                    // 时间已经过期
                    this.getToken()
                        .then(token => {
                            this.dealToken(m, token, timestampNow)
                                .then(data => {
                                    reslove(data, token)
                                })
                        })
                } else {
                    // 时间没有过期
                    this.dealToken(m, this.tokendata.token, timestampNow)
                        .then(data => {
                            reslove(data, this.tokendata.token)
                        })
                }
            } else {
                // 没有token
                this.getToken()
                    .then(token => {
                        this.dealToken(m, token, timestampNow)
                            .then(data => {
                                reslove(data, token)
                            })
                    })
            }

        })
        return rb;
    }
    /**
     * 统一处理数据
     */
    handleData(m) {
        let hb = new Promise((reslove, reject) => {
            if (m && m.hideToken) {
                m.hideToken = undefined
                reslove(m)
            } else {
                let timestampNow = Date.parse(new Date()) / 1000;
                if (this.token) {
                    let min = (timestampNow - this.tokenTimestamp);
                    let i = this.ExpirationDate || 1800;
                    if (min > i) {
                        // 时间已经过期
                        this.getUser({
                            userpwd: this.userpwd,
                            username: this.username
                        })
                            .then(t => {
                                reslove({
                                    ...m,
                                    token: this.token
                                })
                            })
                    } else {
                        // 时间没有过期
                        reslove({
                            ...m,
                            token: this.token
                        })
                    }
                } else {
                    this.getUser({
                        userpwd: this.userpwd,
                        username: this.username
                    })
                        .then(t => {
                            reslove({
                                ...m,
                                token: this.token
                            })
                        })
                }
            }
        })
        return hb
    }
    // 登录用户信息
    getUser(user) {
        this.setApiData('login', {
            password: user.password,
            userName: user.userName
        })
        let rb = new Promise((reslove, reject) => {
            this.post('loginFace', {
                passWord: user.password,
                userName: user.userName
            }).then(r => {
                r.accu[0].dataAreaCode = r.accu[0].dataAreaCode.replace(/((00)|(000))$/, '')
                let timestampNow = Date.parse(new Date()) / 1000;
                this.setApiData('tokendata', {
                    token: r.Data[0].token,
                    timestamp: timestampNow
                })
                this.setApiData('areachoosecodeName', r.accu[0].administrativeDivision)
                this.setApiData('areachoosecode', r.accu[0].administrativeDivisionCode)
                this.setApiData('userinfo', r)
                reslove(r)
            }).catch(err => {
                reject()
            })
        })
        return rb
    }
    // 获取区划
    getZoing() {
        let rb = new Promise((reslove, reject) => {
            this.post(this.interport.host + '/region/tree_list').then(r => {
                this.setApiData('tree_list', r.list)
                reslove(r.list)
            }).catch(err => {
                reject()
            })
        })
        return rb
    }
    // 获取数据字典
    getDictionaries() {
        let rb = new Promise((reslove, reject) => {
            this.post(this.interport.host + '/mobile/mobileDynaTable.shtml?act=selectConfigureTableNew').then(r => {
                this.setApiData('ocndictionaries', r)
                if (window.api) {
                    let reta = r
                    //如果下载成功则写入文件
                    var cacheDir = api.cacheDir;
                    api.writeFile({
                        path: cacheDir + 'config.json',
                        data: JSON.stringify(reta),
                        append: false,
                    }, function (ret, err) {
                        if (ret.status) {
                            $api.setStorage('settingdata', JSON.stringify(reta))
                            //记录写入成功标记
                            api.setPrefs({
                                key: 'isHasConfig',
                                value: true
                            });
                            api.toast({
                                msg: '更新完成',
                                duration: 3000,
                                location: 'bottom'
                            });
                            setTimeout(() => {
                                reslove(r)
                            }, 2000)
                        } else {
                            alert("缓存本地失败")
                        }
                    });
                } else {
                    reslove(r)
                }
            }).catch(err => {
                reject()
            })
        })
        return rb
    }
    // 获取通知消息
    getnews() {
        let year = new Date().getFullYear();
        let month = new Date().getMonth() + 1 < 10 ? "0" + (new Date().getMonth() + 1) : new Date().getMonth() + 1;
        let date = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate();
        // 获取当前时间
        let nowTime = year + "-" + month + "-" + date;
        // 获取前两个月的时间
        let PreviousMonth = month - 2;
        let monthsAgo = PreviousMonth + 1 < 10 ? "0" + (PreviousMonth + 1) : PreviousMonth + 1;
        let PreviousMonthTime = year + "-" + monthsAgo + "-" + date;
        //请求数据
        let r = new Promise((reslove, reject) => {
            this.get('NoticeAnnouncementList', {
                startTime: PreviousMonthTime,
                endTime: nowTime
            }).then(r => {
                reslove(r)
            })
        })
        return r
    }
    // 替换图片等文件的url
    pic(url) {
        if (url) {
            if (url.substring(0, 4) == 'http') {
                return url
            } else {
                return (this.interport.host + url)
            }
        } else {
            return ""
        }

    }
    // 隐藏身份证显示
    delId(card) {
        return card.replace(/^(.{4})(?:\d+)(.{4})$/, "$1******$2");
    }
    // 打卡配置
    __initPunch() {
        if (window.api) {
            if (window.localStorage.getItem('userinfo')) {
                var data = JSON.parse(window.localStorage.getItem('userinfo'))
                $api.setStorage('userData', data.Data[0]);
                $api.setStorage('userinf', data.accu[0]);
            }
        }
    }
    setData(name, data) {
        if (window.api) {
            api.setPrefs({
                key: name,
                value: data
            });
        } else {
            window.localStorage.setItem(name, data)
        }
    }
    getData(name) {
        if (window.api) {
            return api.getPrefs({
                sync: true,
                key: name
            });
        } else {
            return window.localStorage.getItem(name)
        }
    }
    // 微信的权限认证
    checkJsSdk() {
        let rb = new Promise((reslove, reject) => {
            this.post('/wechat/WeChatInterface.shtml', {
                act: 'getSecurity_WeChat',
                url: 'http://ocn.wechat.thinghigh.cn/kunshan/index.html'
            }).then(r => {

            }).catch(
                reject('接口调用失败')
            )
        })
        return rb
    }
    /**
     * 
     * 获取数据字典
     */
    getDictionary() {
        let rb = new Promise((reslove, reject) => {
            if (true) {
                Toast.loading({
                    message: "数据字典加载中...",
                    forbidClick: true
                });
                this.get(
                    "/mobile/mobileDynaTable.shtml?act=selectConfigureTableNew"
                ).then(r => {
                    Toast.clear();
                    window.localStorage.setItem("ConfigureTableNew", JSON.stringify(r));
                    reslove(r);
                }).catch(e => {
                    reject(e)
                });
            } else {
                let dictionary = JSON.parse(window.localStorage.getItem('ConfigureTableNew'));
                reslove(dictionary)
            }
        });
        return rb;
    }
    /**
     * 
     * 根据key值，筛选数据字典
     */
    getDictionaryValus(dictionary) {
        let rb = new Promise((reslove, reject) => {
            if (dictionary) {
                this.getDictionary().then(dictionaries => {
                    let options = [];
                    dictionaries.data.forEach(e => {
                        if (e.parentKey == dictionary) {
                            options.push({
                                text: e.extendAttributeValue,
                                value: e.extendAttributeKey
                            })
                        }
                    });
                    reslove(options);
                }).catch(e => {
                    reject(e)
                })
            } else {
                reject('请填写key值')
            }

        });
        return rb;
    }
    /**
     * 
     * 判断浏览器环境
     */
    isWebview() {
        if (window.api) {
            return 'apicloud';
        }
        let ua = navigator.userAgent;
        let isAndroid = /android/i.test(ua);
        let isIOS = /(iPhone|iPad|iPod|IOS)/i.test(ua);
        let isWechat = /microMessenger/i.test(ua);
        if (isWechat) {
            if (isAndroid) {
                return 'wechat-android';
            }
            if (isIOS) {
                return 'wechat-ios';
            }
        } else {
            return 'others';
        }
    }
    // 权限查看
    Jurisdiction(jd) {
        function del(jd, reslove, reject) {
            if (jd.name == '注销' || jd.name == '删除' || jd.name === '取消注销' || jd.name === '退出登录') {
                jd.dom.$createDialog({
                    type: 'confirm',
                    icon: '',
                    title: '请问确定是否' + jd.name + '?',
                    content: '',
                    confirmBtn: {
                        text: '确定',
                        active: true,
                        disabled: false,
                        href: 'javascript:;'
                    },
                    cancelBtn: {
                        text: '取消',
                        active: false,
                        disabled: false,
                        href: 'javascript:;'
                    },
                    onConfirm: () => {
                        reslove()
                    },
                    onCancel: () => {
                        reject()
                    }
                }).show()
            } else {
                reslove();
            }
        }
        // 获取主要域名
        let host = this.interport.host;
        let ids = this.userinfo.accu[0].accountId;
        let tokenArr = this.tokendata
        let r = new Promise((reslove, reject) => {
            if (jd.test) {
                del(jd, reslove, reject)
            } else if (jd.name === '编辑' || jd.name === '删除' || jd.name === '注销' || jd.name === '取消注销') {
                // 判断url 是不是http开头
                let url = host + jd.url;
                // 数据处理
                if (window.api) {
                    api.ajax({
                        url: url,
                        method: 'post',
                        data: {
                            values: {
                                ids: ids,
                                token: tokenArr.token
                            }
                        }
                    }, function (ret, err) {
                        if (ret) {
                            if (ret.success) {
                                del(jd, reslove, reject)
                            } else {
                                jd.dom.ocn.warn_toast(jd.dom).show('您还没有权限' + jd.name)
                                reject()
                            }
                        } else {
                            jd.dom.ocn.warn_toast(jd.dom).show('您还没有权限' + jd.name)
                            reject();
                        }
                    });
                } else {
                    let postData = qs.stringify({
                        ids: ids,
                        token: tokenArr.token
                    });
                    axios.post(url, postData)
                        .then(r => {
                            if (r.data.success) {
                                del(jd, reslove, reject)
                            } else {
                                jd.dom.ocn.warn_toast(jd.dom).show('您还没有权限' + jd.name)
                                reject()
                            }
                        })
                        .catch(e => {
                            jd.dom.ocn.warn_toast(jd.dom).show('您还没有权限' + jd.name)
                            reject()
                        })
                }
            } else {
                reslove()
            }
        });
        return r;
    }
    // 保留当前页面跳转新的页面
    navigateTo(url, name, data) {
        if (window.api) {
            api.openWin({
                name: name || 'ocn',
                url: url,
                pageParam: data || ''
            });
        } else {
            window.open(url)
        }
    }
    getTime(type = 'datetime', dateOrigin) {
        var d = new Date();
        if (dateOrigin) {
            d = dateOrigin;
        }
        var year = d.getFullYear();
        var month = change(d.getMonth() + 1);
        var day = change(d.getDate());
        var hour = change(d.getHours());
        var minute = change(d.getMinutes());
        var second = change(d.getSeconds());

        function change(t) {
            if (t < 10) {
                return "0" + t;
            } else {
                return t;
            }
        }
        if (type === 'datetime') {
            var datetime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
            return datetime;
        } else if (type === 'date') {
            var date = year + '-' + month + '-' + day;
            return date;
        } else if (type === 'time') {
            var time = hour + ':' + minute + ':' + second;
            return time;
        }
    }
    // 关闭当前窗口，跳转新的窗口
    redirectTo(url, name, data) {
        if (window.api) {
            api.openWin({
                name: name || 'ocn',
                url: url,
                pageParam: data || ''
            });
            setTimeout(function () {
                var windows = api.windows();
                // api.alert({
                //     msg:JSON.stringify(windows)
                // });
                // alert(windows[1].name)
                if (windows.length > 1) {
                    // alert(windows[1].name)
                    api.closeWin({
                        name: windows[1].name
                    });
                }
            }, 5000);
        } else {
            window.location.href = url
        }
    }
}